package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import pojo.Result;
import pojo.SysUser;
import service.SysUserService;
import service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/user/*")
@SuppressWarnings("ALL")
public class SyncUserController extends HttpServlet {

    // 使用接口接收
    private SysUserService userService =new SysUserServiceImpl();


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("GBK");
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        String methodName = split[split.length - 1];

        if (methodName.equals("login")) {
            //用户登录的业务逻辑
            login(request, response);
        }else if (methodName.equals("register")) {
            // 用户注册的业务逻辑
            register(request, response);
        }else if (methodName.equals("checkUserNameUsed")) {
            checkUsernameUsed(request, response);
        }


    }

    /**
     * 接收用登录请求,完成的登录业务接口
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1 接收用户名和密码
        String username = request.getParameter("username");
        String userPwd = request.getParameter("userPwd");

        // 1. 接收客户端提交的 json 参数 并转化为 User 对象
        BufferedReader reader = request.getReader();
        StringBuffer sb = new StringBuffer();
        String line = reader.readLine();
        while (line != null) {
            sb.append(line);
            line = reader.readLine();
        }

        ObjectMapper mapper = new ObjectMapper();
        SysUser user = mapper.readValue(sb.toString(), SysUser.class);
        System.out.println(user.getUsername());
        username = user.getUsername();
        userPwd = user.getUserPwd();

        //2 调用服务层方法,根据用户名查询用户信息
        SysUser loginUser =userService.findByUsername(username);
        Result result;
        if(null == loginUser){
            // 跳转到用户名有误提示页 返回状态码
             result = new Result<>("501", "用户名有误", null);

        }else if( !userPwd.equals(loginUser.getUserPwd()) ){
            //3 判断密码是否匹配
            // 跳转到密码有误提示页
            // 跳转到用户名有误提示页 返回状态码
             result = new Result<>("503", "密码有误", null);
        }else{
            //4 跳转到首页
            // 1. 登录成功后 需要将用户的登录状态 保存到 会话域里面
            HttpSession session = request.getSession();
            session.setAttribute("user", loginUser);
            result = new Result<>("200", "登录成功", loginUser.getUsername());
        }

        // 转换成为 JSON 返回前端
        String json = mapper.writeValueAsString(result);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json);


    }

    /**
     * 用户注册相关
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 接收用户名和密码
        String username = request.getParameter("username");
        String userPwd = request.getParameter("userPwd");

        // 1. 接收客户端提交的 json 参数 并转化为 User 对象
        BufferedReader reader = request.getReader();
        StringBuffer sb = new StringBuffer();
        String line = reader.readLine();
        while (line != null) {
            sb.append(line);
            line = reader.readLine();
        }

        ObjectMapper mapper = new ObjectMapper();
        SysUser user = mapper.readValue(sb.toString(), SysUser.class);
        System.out.println(user.getUsername());
        username = user.getUsername();
        userPwd = user.getUserPwd();

        // 注册之前先查一下库
        //2 调用服务层方法,根据用户名查询用户信息
        Result result;
        SysUser loginUser =userService.findByUsername(username);
        if(loginUser != null ){
            // 说明这个账号已经被注册过了 那就需要跟换一个
            // response.sendRedirect("/registerFail.html");
            result = new Result("500", "昵称以占用", null);
        }else {
            // 说明这个账号还没被注册过，去注册
            int reg = userService.regist(new SysUser(username, userPwd));
            result = new Result("200", "注册成功！", null);

        }

        // 转换成为 JSON 返回前端
        String json = mapper.writeValueAsString(result);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(json);
    }

    /**
     * 用户名是否占用校验
     */
   public void checkUsernameUsed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.setCharacterEncoding("utf-8");
       String username = request.getParameter("username");
       SysUser loginUser =userService.findByUsername(username);
       String info = "可用";
       if(loginUser != null){
           info = "已占用";
       }
       response.getWriter().print(info);
   }

}
